package com.charles.seckillsystem.rocketMQ.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.charles.seckillapi.domain.SysGood;
import com.charles.seckillapi.domain.SysOrder;
import com.charles.seckillcommon.core.constants.CacheConstants;
import com.charles.seckillcommon.core.utils.StringUtils;
import com.charles.seckillcommon.redis.service.RedisService;
import com.charles.seckillsystem.mapper.SysOrderMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Charles-H
 * 
 * 订单消费者
 */
@Component
@RocketMQMessageListener(topic = "checkOrder", consumerGroup = "checkOrderGroup")
public class OrderConsumer implements RocketMQListener<String> {

    @Resource
    private SysOrderMapper sysOrderMapper;
    
    @Autowired
    private RedisService redisService;
    
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void onMessage(String s) {
        Map<String, Long> map = JSONObject.parseObject(s, Map.class);
        String userId = String.valueOf(map.get("userId"));
        String goodId = String.valueOf(map.get("goodId"));
        String orderId = (String) redisService.getCacheObject(CacheConstants.STORE_ORDER_ID + userId + goodId);

        if (StringUtils.isNotEmpty(orderId)) {
            SysOrder order = (SysOrder) redisService.getCacheObject(CacheConstants.ORDER_ID + orderId);
            if (StringUtils.isNotNull(order)) {
                if (order.getStatus().equals("1")) {
                    // 如果订单已支付,存入数据库
                    sysOrderMapper.addOrder(order);
                } else {
                    // 如果订单未支付,则让增加产品库存
                    RLock lock = redissonClient.getLock("seckill");
                    try {
                        lock.lock();
                        SysGood good = (SysGood) redisService.getCacheObject(CacheConstants.GOOD_ID + goodId);
                        if (good != null) {
                            good.setRemain(good.getRemain() + 1);
                            redisService.setCacheObject(CacheConstants.GOOD_ID + goodId, good);
                        }
                    } finally {
                        lock.unlock();
                    }
                }
                redisService.deleteObject(CacheConstants.STORE_ORDER_ID + userId + goodId);
                redisService.deleteObject(CacheConstants.ORDER_ID + orderId);
            }
        }

    }
}
